this
Keyword in JavaScriptThe this
keyword in JavaScript refers to the object it belongs to. It has different meanings depending on the context in which it is used.
In the global context, this
refers to the global object, which is window
in browsers.
console.log(this); // Refers to the global window object
Output: Window object
When used in a method, this
refers to the object that owns the method.
const obj = {
name: "JavaScript",
greet: function() {
return `Hello, ${this.name}!`;
}
};
console.log(obj.greet());
Output: Hello, JavaScript!
In a constructor function, this
refers to the instance of the object created by the constructor.
function Person(name) {
this.name = name;
}
const person = new Person("Alice");
console.log(person.name);
Output: Alice
Arrow functions do not have their own this
; they inherit it from the surrounding lexical scope.
const obj = {
name: "JS",
greet: () => {
console.log(this.name); // Inherits `this` from the global scope
}
};
obj.greet();
Output: Undefined (or inherited from the global scope)
this
is context-dependent in JavaScript.this
and inherit it from the lexical scope.